package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ZSetOperations<String,String> opsForZSet = redisTemplate.opsForZSet();
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            log.error("获取用户失败，请登录");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
//            redisTemplate.multi();
            if (dto.getOperation().intValue()==0){
                Double score = opsForZSet.score(UserRelationConstants.FOLLOW_LIST + user.getId(), dto.getAuthorApUserId().toString());
                if (score != null){
                    log.error("不能重复关注");
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST);
                }
                if (user.getId()==dto.getAuthorApUserId()){
                    log.error("不能关注自己");
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
                }
                //            关注列表增加
                opsForZSet.add(UserRelationConstants.FOLLOW_LIST+user.getId(),
                        dto.getAuthorApUserId().toString(),
                        System.currentTimeMillis());
    //            粉丝列表增加
                opsForZSet.add(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),
                        user.getId().toString(),
                        System.currentTimeMillis());
            }else {
    //            关注列表减少
                opsForZSet.remove(UserRelationConstants.FOLLOW_LIST+user.getId(),
                        dto.getAuthorApUserId().toString());
    //            粉丝列表减少
                opsForZSet.remove(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),
                        user.getId().toString());
            }
//            redisTemplate.exec();
        } catch (Exception e) {
            e.printStackTrace();
//            redisTemplate.discard();
        }
        return ResponseResult.okResult();
    }
}
